﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; 
using System.Xml;

namespace Belyn.Common.Xml
{
    public class XmlOperate:IXmlOperate
    {


        protected System.Xml.XmlDocument XmlDoc;
        protected string RootNodename;
        protected string XmlFilePath;
        protected XmlOperate(string xml_filename)
        {
            try
            {
                this.XmlFilePath = xml_filename;
                this.XmlDoc = new XmlDocument();
                this.XmlDoc.Load(xml_filename);
                this.RootNodename = this.XmlDoc.DocumentElement.Name + "/";

            }
            catch (Exception ex)
            {
                throw new Exception("加载xml文件 <" + xml_filename + "> 失败，请确保路径的正确！");
            }
        }

        #region IXmlOperate 成员

        public string Read(string path)
        {
            return this[path];
        }

        public void Write(string path, string val)
        {
            this.GetNode(path).InnerText = val;
            this.Save();
        }

        public string ReadAttribute(string path, string attrName)
        {
            return this[path, attrName];
        }

        public void WriteAttribute(string path, string attrName, string val)
        {
            this.GetNodeAttr(path,attrName).InnerText = val;
            this.Save();
        }

        public XmlNodeList GetNodeList(string path)
        {
            return this.XmlDoc.SelectNodes(string.Format("{0}{1}", this.RootNodename, path));
        }
        public XmlNode GetNode(string path)
        {
            return this.XmlDoc.SelectSingleNode(string.Format("{0}{1}", this.RootNodename, path));
        }
        #endregion

        public virtual string this[string configName]
        {
            get
            {
                return this.XmlDoc.SelectSingleNode(string.Format("{0}{1}", this.RootNodename, configName)).InnerText;
            }
        }

        public virtual string this[string configName, string attrName]
        {
            get
            {
                return this.XmlDoc.SelectSingleNode(string.Format("{0}{1}", this.RootNodename, configName))
                                                    .Attributes.GetNamedItem(attrName).InnerText;
            }

        }

        protected virtual void Save()
        {
            this.XmlDoc.Save(XmlFilePath);
        }

       

        protected XmlNode GetNodeAttr(string configName, string attrName)
        {
            return this.XmlDoc.SelectSingleNode(string.Format("{0}{1}", this.RootNodename, configName))
                                                    .Attributes.GetNamedItem(attrName);
        }


        public static XmlOperate Load(string xmlFilename)
        {
            return new XmlOperate(xmlFilename);
        }
    }
}
